﻿using PaperMaster.Chess.ChessModel;
using PaperMaster.Info;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace PaperMaster.Chess
{
    public class ChessBoardViewController : MonoBehaviour
    {
        public static ChessBoardController GetController()
        {
            GameObject board = GameObject.Find("ChessBoard");
            if (board != null)
            {
                return board.GetComponent<ChessBoardViewController>().controller;
            }
            return null;
        }
        public ChessBoardController controller;
        // Start is called before the first frame update
        void Start()
        {
            Init();
        }

        // Update is called once per frame
        void Update()
        {
            FrameFun();
        }

        public virtual void Init()
        {
            controller = new ChessBoardController();
        }

        protected virtual void FrameFun()
        {
            CheckSelect();
        }

        /// <summary>
        /// 检测玩家选择棋盘块
        /// </summary>
        void CheckSelect()
        {
            if (Input.GetMouseButtonDown(0))
            {//判断鼠标是否按下
             // 从摄像机开始，到屏幕触摸点，发出一条射线
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                // 撞击到了哪个3D物体
                RaycastHit hit;
                if (Physics.Raycast(ray, out hit))
                {
                    ChessBlockModel block = controller.model.Board.selectedBlock;
                    if (block != null)
                    {
                        ///撤销
                        block.viewController.controller.OnDeSelect();
                    }
                    if (hit.transform.GetComponent<ChessBlock>() != null)
                    {
                        controller.model.Board.selectedBlock = hit.transform.GetComponent<ChessBlock>().controller.model;
                        controller.model.Board.selectedBlock.viewController.controller.OnSelect();
                    }
                    AbstractFightInfoViewController.GetController().UpdateUI("Block");
                }
                else
                {
                    ChessBlockModel block = controller.model.Board.selectedBlock;
                    if (block != null)
                    {
                        ///撤销
                        block.viewController.controller.OnDeSelect();
                    }
                }
            }
        }
    }
}
